import os
import re
from pathlib import Path
import json
import pandas as pd


def get_image_features(path):
    path = Path(path)
    result = {}
    image_name = []

    if not path.exists():
        result['diagnosisResult'] = []
        return result

    for image_path in path.parent.iterdir():
        # 只处理图片文件
        if image_path.is_file() and image_path.suffix.lower() in ['.jpg', '.jpeg', '.png']:
            image_name.append(image_path.name)

    df = pd.read_excel(path)
    for index, row in df.iterrows():
        if row['图片名称'] in image_name:
            cols_with_1 = [df.columns[i] for i, val in enumerate(row) if val == 1]
            result[row['图片名称']] = cols_with_1
        if row['图片名称'] == '诊断结果':
            diagnosis_result = []
            if type(row['方向左侧']) == str:
                for s in row['方向左侧'].split(';'):
                    diagnosis_result.append(re.sub(r'\d+', '', s))
                result['diagnosisResult'] = diagnosis_result

    if result.get('diagnosisResult') is None:
        result['diagnosisResult'] = []

    return result


def get_image_feature(image_path, excel_path):
    image_path = Path(image_path)
    excel_path = Path(excel_path)
    result = {}

    df = pd.read_excel(excel_path)
    for index, row in df.iterrows():
        if row['图片名称'] in image_path.name:
            cols_with_1 = [df.columns[i] for i, val in enumerate(row) if val == 1]
            field = replace_field(cols_with_1)
            result[row['图片名称']] = field
        if row['图片名称'] == '诊断结果':
            diagnosis_result = []
            for s in row['方向左侧'].split(';'):
                diagnosis_result.append(re.sub(r'\d+', '', s))
            result['diagnosisResult'] = diagnosis_result

    if result.get('diagnosisResult') is None:
        result['diagnosisResult'] = []

    return result


def replace_field(str_list):
    mapping = {
        # 添加不同写法的映射（关键部分：左侧偏曲 → 偏曲左侧）
        '鼻中隔左侧偏曲': '鼻中隔偏曲左侧',  # 输入"左侧偏曲" → 输出"偏曲左侧"
        '鼻中隔右侧偏曲': '鼻中隔偏曲右侧',  # 输入"右侧偏曲" → 输出"偏曲右侧"
        '鼻中隔S型偏曲': '鼻中隔偏曲S型',
        '鼻中隔左侧嵴突': '鼻中隔嵴突左侧',
        '鼻中隔右侧嵴突': '鼻中隔嵴突右侧',
        '鼻中隔左侧棘突': '鼻中隔棘突左侧',
        '鼻中隔右侧棘突': '鼻中隔棘突右侧',
        '鼻中隔左侧黎氏区充血': '鼻中隔黎氏区充血左侧',
        '鼻中隔右侧黎氏区充血': '鼻中隔黎氏区充血右侧',
        '鼻中隔左侧鼻中隔穿孔': '鼻中隔鼻中隔穿孔左侧',
        '鼻中隔右侧鼻中隔穿孔': '鼻中隔鼻中隔穿孔右侧',
    }
    for s in str_list:
        if s in mapping:
            str_list[str_list.index(s)] = mapping[s]

    return str_list  # 如果匹配则返回标准化值，否则返回None


def get_patient_diagnosis(path):
    path = Path(path)
    result = {}
    patient_names = []

    for patient_path in path.parent.iterdir():
        # 只处理文件夹
        if patient_path.is_dir():
            patient_names.append(patient_path.name)

    if not path.exists():
        for patient_name in patient_names:
            result[patient_name] = {
                "diagnosis": '',
                "checkingProcess": '',
            }

    df = pd.read_excel(path)
    for patient_name in patient_names:
        for index, row in df.iterrows():
            if row['姓名_日期_门诊号_拼音'] == patient_name:
                result[patient_name] = {
                    "diagnosis": row['检查诊断'],
                    "checkingProcess": row['检查过程'],
                }

    return result


def get_real_path(path, split_regex):
    split = path.split(split_regex)
    sys_path = ''
    for s in split:
        sys_path += s + os.path.sep

    return sys_path


def get_child_folders(path):
    """
    获取目标路径的子文件夹列表
    :param path: 目标路径
    :return: 子文件夹列表
    """
    path = Path(path)
    result = []
    for item in path.iterdir():
        if item.is_dir():
            result.append(item.name)
    return result


def get_child_file_list(path, file_types=None):
    """
    获取目标路径的子文件列表
    :param path: 目标路径
    :param file_types: 文件类型列表，默认为None，表示获取所有文件
    :return: 子文件列表
    """
    path = Path(path)
    result = []
    for item in path.iterdir():
        if item.is_file():
            if file_types is None or item.suffix.lower() in file_types:
                result.append(item.name)
    return result


def get_json_from_excel(excel_path):
    """
    从Excel文件中读取数据并转换为JSON格式
    :param excel_path: Excel文件路径
    :return: JSON格式的数据
    """
    # 读取Excel文件
    df = pd.read_excel(excel_path)
    transform_arr = {}
    d_res = ''
    for index, row in df.iterrows():
        if row['图片名称'] == '诊断结果':
            d_res = row['方向左侧']
            break

    for index, row in df.iterrows():
        groups = {
            '方向': [],
            '鼻腔粘膜': [],
            '鼻中隔': [],
            '总鼻道/鼻腔': [],
            '下鼻甲': [],
            '中鼻甲': [],
            '中鼻道': [],
            '嗅裂': [],
            '鼻咽': [],
            '图片质量': []
        }
        image_name = row['图片名称']
        if image_name == '诊断结果':
            continue
        json_data = {
            image_name: groups,
        }
        for column_name in row.keys():
            for group_name in groups.keys():
                if group_name in column_name:
                    # data = row[column_name] if not pd.isna(
                    #     row[column_name]) else 1
                    data = row[column_name] if not pd.isna(row[column_name]) else 0
                    json_data[image_name][group_name].append(
                        {
                            column_name.replace(group_name, ''): int(data)
                        }
                    )
        transform_arr[image_name] = groups
    split = d_res.split(';')
    re_split = []
    for s in split:
        rs = re.sub(r'\d+', '', s)
        re_split.append(rs)

    transform_arr['诊断结果'] = re_split
    return transform_arr


replace_list = ["鼻中隔左侧偏曲",
                "鼻中隔右侧偏曲",
                "鼻中隔S型偏曲",
                "鼻中隔左侧嵴突",
                "鼻中隔右侧嵴突",
                "鼻中隔左侧棘突",
                "鼻中隔右侧棘突",
                "鼻中隔左侧黎氏区充血",
                "鼻中隔右侧黎氏区充血",
                "鼻中隔左侧鼻中隔穿孔",
                "鼻中隔右侧鼻中隔穿孔", ]

excel_default_column = [
    "图片名称",
    "方向左侧",
    "方向右侧",
    "鼻腔粘膜未见异常",
    "鼻腔粘膜淡红",
    "鼻腔粘膜充血",
    "鼻腔粘膜苍白",
    "鼻腔粘膜水肿",
    "鼻腔粘膜萎缩",
    "鼻中隔未见异常",
    "鼻中隔居中",
    "鼻中隔偏曲左侧",
    "鼻中隔偏曲右侧",
    "鼻中隔偏曲S型",
    "鼻中隔嵴突左侧",
    "鼻中隔嵴突右侧",
    "鼻中隔棘突左侧",
    "鼻中隔棘突右侧",
    "鼻中隔黎氏区充血左侧",
    "鼻中隔黎氏区充血右侧",
    "鼻中隔鼻中隔穿孔左侧",
    "鼻中隔鼻中隔穿孔右侧",
    "总鼻道/鼻腔未见异常",
    "总鼻道/鼻腔分泌物见水样",
    "总鼻道/鼻腔分泌物见脓性",
    "总鼻道/鼻腔分泌物见粘性",
    "总鼻道/鼻腔见肿物暗红",
    "总鼻道/鼻腔见肿物充血",
    "总鼻道/鼻腔见肿物灰白",
    "总鼻道/鼻腔见肿物光滑",
    "总鼻道/鼻腔见肿物不平",
    "总鼻道/鼻腔见肿物粗糙",
    "下鼻甲未见异常",
    "下鼻甲无肿大",
    "下鼻甲下鼻甲肥大",
    "下鼻甲下鼻甲桑甚样改变",
    "下鼻甲下鼻甲息肉样变",
    "下鼻甲下鼻甲缺失",
    "下鼻甲充血",
    "下鼻甲肿胀",
    "中鼻甲未见异常",
    "中鼻甲无肿大",
    "中鼻甲中鼻甲肥大",
    "中鼻甲泡状中鼻甲",
    "中鼻甲中鼻甲息肉样变",
    "中鼻甲中鼻甲缺失",
    "中鼻甲充血",
    "中鼻甲肿胀",
    "中鼻道未见异常",
    "中鼻道充血",
    "中鼻道肿胀",
    "中鼻道分泌物见水样",
    "中鼻道分泌物见脓性",
    "中鼻道分泌物见粘性",
    "中鼻道见肿物暗红",
    "中鼻道见肿物充血",
    "中鼻道见肿物灰白",
    "中鼻道见肿物光滑",
    "中鼻道见肿物不平",
    "中鼻道见肿物粗糙",
    "嗅裂未见异常",
    "嗅裂充血",
    "嗅裂肿胀",
    "嗅裂分泌物见水样",
    "嗅裂分泌物见脓性",
    "嗅裂分泌物见粘性",
    "嗅裂见肿物暗红",
    "嗅裂见肿物充血",
    "嗅裂见肿物灰白",
    "嗅裂见肿物光滑",
    "嗅裂见肿物不平",
    "嗅裂见肿物粗糙",
    "鼻咽未见异常",
    "鼻咽充血",
    "鼻咽肿胀",
    "鼻咽肥大",
    "鼻咽分泌物见水样",
    "鼻咽分泌物见脓性",
    "鼻咽分泌物见粘性",
    "鼻咽见肿物暗红",
    "鼻咽见肿物充血",
    "鼻咽见肿物灰白",
    "鼻咽见肿物光滑",
    "鼻咽见肿物不平",
    "鼻咽见肿物粗糙",
    "图片质量合格",
    "图片质量不合格",
]
